#include "debug.h"
#include "common.h"

GLenum dbgGLPrintLastError(int no)
{
    int err = glGetError();

    DEBUG_OUTPUT("testing %d {", no);

    switch (err)
    {
    case GL_NO_ERROR:
        DEBUG_OUTPUT("no error.}");
        return false;
    case GL_INVALID_ENUM:
        DEBUG_OUTPUT("err: invalid enum.}");
        break;
    case GL_INVALID_VALUE:
        DEBUG_OUTPUT("err: invalid value.}");
        break;
    case GL_INVALID_OPERATION:
        DEBUG_OUTPUT("err: invalid operation.}");
        break;
    case GL_STACK_OVERFLOW:
        DEBUG_OUTPUT("err: stack overflow.}");
        break;
    case GL_STACK_UNDERFLOW:
        DEBUG_OUTPUT("err: stack underflow.}");
        break;
    case GL_OUT_OF_MEMORY:
        DEBUG_OUTPUT("err: out of memory.}");
        break;
    }

    return err;
}

void MsgBox(const char* msg)
{
#ifdef UNDER_CE
    DWORD dwNum = ::MultiByteToWideChar(CP_ACP, 0, msg, -1, NULL, 0);
    wchar_t* pwText;
    pwText = new wchar_t[dwNum];
    ::MultiByteToWideChar(CP_ACP, 0, msg, -1, pwText, dwNum * sizeof(wchar_t));
    ::MessageBoxW(NULL, pwText, pwText, MB_OK);
#else
    const char* pwText = msg;
    ::MessageBoxA(NULL, pwText, pwText, MB_OK);
#endif
}

void initDebugging()
{
    // #ifndef UNDER_CE
    dbgfile = stdout;
    // #else
    //     struct tm* info = currenttime();
    //     char buf[64] = {0};
    //
    //     sprintf_s(buf, 64, "\\NAND\\log\\%02d-%02d-%04dd.log",
    //               info->tm_mon,
    //               info->tm_mday,
    //               info->tm_year);
    //     fopen_s(&dbgfile, buf, "a");
    // #endif

    dbgfile_inited = true;
}

void writeDebugMessage(const char* format, ...)
{
    va_list ap;
    va_start(ap, format);

#ifndef UNDER_CE
    char buf[1024];
    vsprintf_s(buf, 1024, format, ap);
    if (buf[strlen(buf) - 1] != '\n') {
        strcat(buf, "\n");
    }
    OutputDebugStringA(buf);
#else

    if (!dbgfile_inited)
    {
        return;
    }

    struct tm* info = currenttime();
    char buf[1024];

    sprintf(buf, "[%02d/%02d/%04d %02d:%02d:%02d]$",
            info->tm_mon,
            info->tm_mday,
            info->tm_year,
            info->tm_hour,
            info->tm_min,
            info->tm_sec);

    vsprintf(buf, format, ap);
    if (buf[strlen(buf) - 1] != '\n') {
        strcat(buf, "\n");
    }
    fputs(buf, dbgfile);

    // Who can wait for it to flush when fclose!!
    fflush(dbgfile);

#endif
    va_end(ap);
}

void closeDebugfile()
{
    if (!dbgfile_inited)
    {
        return;
    }

    if (dbgfile != stdout)
    {
        fclose(dbgfile);
    }

    dbgfile_inited = false;
}
